import dayjs from 'dayjs';
import fs from 'fs';
import path from 'path';
import { defineConfig, loadEnv } from 'vite';
import checker from 'vite-plugin-checker';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
import vitePluginRequire from 'vite-plugin-require';

import react from '@vitejs/plugin-react';

import packageJson from './package.json';

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());

  const version = `${packageJson.version} [${dayjs().format('YYYY-MM-DD HH:mm:ss')}]`;

  if (mode === 'production') {
    fs.writeFileSync(
      path.resolve(__dirname, 'public/version.json'),
      JSON.stringify({
        version
      }),
      'utf-8'
    );
  }

  return {
    define: {
      emptyText: JSON.stringify(env.VITE_NULL_TEXT),
      // 注入版本信息,方便比较
      VERSION: JSON.stringify(version)
    },
    server: {
      open: true,
      port: 3288,
      proxy: {
        // 选项写法
        [env.VITE_PROXY_KEY]: {
          target: env.VITE_SERVER_URL,
          changeOrigin: true,
          rewrite: (path) => {
            return path.replace(new RegExp(addCaretToRegex(env.VITE_PROXY_KEY)), '');
          }
        },
        // 业务
        '/socket.io/': {
          target: env.VITE_SOCKET_URL,
          // target: "http://192.168.100.150/",
          changeOrigin: true,
          ws: true
        }
      },
      host: true, // 监听所有地址
      watch: {
        usePolling: true // 修复HMR热更新失效
      }
    },
    base: './',
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src')
        // "socket.io-client": "socket.io-client/dist/socket.io.js",
      }
    },
    // css
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import '@/styles/import.scss';`
        }
      }
    },
    plugins: [
      react(),
      checker({
        typescript: {
          buildMode: true
        }
      }),
      nodePolyfills(),
      (vitePluginRequire as unknown as { default: typeof vitePluginRequire }).default()
    ],
    optimizeDeps: {
      exclude: ['hash-worker'] // new added
    }
  };
});

// 把/api/转换成^/api
function addCaretToRegex(str: string): string {
  const regex = new RegExp(str);
  return regex.toString().replace(/^\/(.*)\/$/, '^$1');
}
